<template>
  <view class="settled container">
    <!-- 入驻 -->
    <u--form
      labelPosition="left"
      labelWidth="100px"
      :model="technicianInfo"
      :rules="rules"
      ref="userForm"
    >
      <u-form-item label="姓名" prop="name" borderBottom required>
        <u--input v-model="technicianInfo.name" border="none"></u--input>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="技师昵称" prop="nickname" borderBottom required>
        <u--input v-model="technicianInfo.nickname" border="none"></u--input>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="性别" prop="sex" borderBottom required>
        <u-radio-group
          slot="right"
          size="18px"
          iconSize="10"
          activeColor="#C94117"
          v-model="technicianInfo.sex"
          @change="groupChange"
          placement="row"
        >
          <u-radio
            :customStyle="{ marginRight: '20px' }"
            v-for="(item, index) in radiolist1"
            :key="index"
            :label="item.name"
            :name="item.name"
          >
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="联系方式" prop="phone" borderBottom required>
        <u--input v-model="technicianInfo.phone" border="none"></u--input>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="紧急联系人" prop="urgent_phone" borderBottom required>
        <u--input
          v-model="technicianInfo.urgent_phone"
          border="none"
        ></u--input>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="从业年限" prop="dateRange" borderBottom required>
        <u--input v-model="technicianInfo.dateRange" border="none"></u--input>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="意向城市" prop="city" borderBottom required>
        <u--input v-model="technicianInfo.city" border="none"></u--input>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item
        label="所在地址"
        prop="address"
        borderBottom
        required
        @click="chooseLocation"
      >
        <view>{{ technicianInfo.address }}</view>
        <!-- <u--input v-model="technicianInfo.address" border="none"></u--input> -->
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item
        label="技师简介"
        labelPosition="top"
        prop="introduction"
        borderBottom
      >
        <u--textarea
          v-model="technicianInfo.introduction"
          count
          :maxlength="500"
          placeholder="请输入内容"
        ></u--textarea>
      </u-form-item>
      <u-form-item label="身份证号" prop="idCard" borderBottom required>
        <u--input v-model="technicianInfo.idCard" border="none"></u--input>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item
        label="身份证照片(正反)"
        labelWidth="150px"
        labelPosition="top"
        prop="idCard_img"
        required
      >
        <u-upload
          :fileList="fileList1"
          @afterRead="afterRead"
          @delete="deletePic"
          name="1"
          multiple
          :maxCount="2"
        ></u-upload>
      </u-form-item>
      <u-form-item
        label="资格证书"
        labelPosition="top"
        prop="certificate_img"
        required
      >
        <u-upload
          :fileList="fileList2"
          @afterRead="afterRead"
          @delete="deletePic"
          name="2"
          multiple
          :maxCount="1"
        ></u-upload>
      </u-form-item>
      <u-form-item
        label="工作形象照"
        labelPosition="top"
        prop="work_img"
        required
      >
        <u-upload
          :fileList="fileList3"
          @afterRead="afterRead"
          @delete="deletePic"
          name="3"
          multiple
          :maxCount="1"
        ></u-upload>
      </u-form-item>
    </u--form>

    <button class="circle-button btn-active" style="width: 90%" @click="submit">
      提交
    </button>

    <u-modal
      title="免责协议"
      :show="showModel"
      @close="showModel = false"
      closeOnClickOverlay
      showCancelButton
    >
      <view class="slot-content">
        <rich-text :nodes="content"></rich-text>

        <view style="margin: 20rpx 0 40rpx 0">
          <u-checkbox-group
            v-model="switchVal"
            shape="circle"
            activeColor="#C94117"
          >
            <u-checkbox
              name="1"
              label="我已阅读并同意"
              :customStyle="{ marginLeft: '0' }"
            >
            </u-checkbox>
          </u-checkbox-group>
        </view>
      </view>

      <button
        slot="confirmButton"
        class="circle-button btn-active"
        style="width: 90%"
        @click="submitUserForm"
      >
        确定
      </button>
    </u-modal>
  </view>
</template>

<script>
import { createModel, updateModel, getModelList } from "@/api";
import { UpdateFilePath } from "@/api/file";
import { getSearchFilter } from "@/common/function";
import config from "@/common/config";
export default {
  data() {
    return {
      showSex: false,
      technicianInfo: {
        name: "",
        nickname: "",
        sex: "男",
        phone: "",
        urgent_phone: "", //紧急联系人电话
        dateRange: "",
        city: "",
        address: "",
        technician_address: "",
        introduction: "",
        idCard: "",
        // 省份证照片
        idCard_img: [],
        // 资格证书
        certificate_img: [],
        // 工作形象照
        work_img: [],
      },
      rules: {
        name: {
          type: "string",
          required: true,
          message: "请填写姓名",
          trigger: ["blur", "change"],
        },
        nickname: {
          type: "string",
          required: true,
          message: "请填写技师昵称",
          trigger: ["blur", "change"],
        },
        sex: {
          type: "string",
          required: true,
          message: "请选择性别",
          trigger: ["change"],
        },
        phone: [
          {
            type: "string",
            required: true,
            message: "请填写联系方式",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            trigger: ["change", "blur"],
          },
        ],
        dateRange: [
          {
            validator: (rule, value, callback) => {
              const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
              let arr = value.split(",");
              return (
                arr.every(
                  (item) => uni.$u.test.date(item) && dateRegex.test(item)
                ) && arr.length > 1
              );
            },
            message: "请填写正确年限 格式:2024-01-10,2025-01-10",
            trigger: ["change", "blur"],
          },
        ],
        city: {
          type: "string",
          required: true,
          message: "请填写城市",
          trigger: ["blur", "change"],
        },
        address: {
          type: "string",
          required: true,
          message: "请填写地址",
          trigger: ["blur", "change"],
        },
        idCard: [
          {
            type: "string",
            required: true,
            message: "请填写身份证号",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.idCard(value);
            },
            message: "身份证号不正确",
            trigger: ["change", "blur"],
          },
        ],
        idCard_img: [
          {
            type: "array",
            required: true,
            min: 2,
            message: "请上传身份证正反照片",
            trigger: ["change"],
          },
          // {
          //   validator: (rule, value, callback) => {
          //     // console.log(value);
          //     console.log("数组1", this.fileList1);
          //   },
          //   trigger: ["change"],
          //   message: '必须包含字母"A"',
          // },
        ],
        certificate_img: {
          type: "array",
          required: true,
          message: "请上传资格证书",
          trigger: ["change"],
        },
        work_img: {
          type: "array",
          required: true,
          message: "请上传工作形象照",
          trigger: ["change"],
        },
      },
      switchVal: false,
      // 按钮
      radiolist1: [
        {
          name: "男",
          disabled: false,
        },
        {
          name: "女",
          disabled: false,
        },
      ],
      // 身份证照片数组
      fileList1: [],
      // 资格证书数组
      fileList2: [],
      // 工作形象照数组
      fileList3: [],
      // 模态框
      showModel: false,
      // 内容
      content: `<p style="color: #666666;font-size: 24rpx;">商品均经过严格的包装后发出，运输如有破损，请不用担心，联系我们即口免费补发。如出现漏发现象，我们将无条行核查后免费补发。</p>`,
      currentName: -1,
      // 技师id
      technicianId: "",
    };
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    // 上传请求
    uploadFilePromise(url) {
      let that = this;
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: config.baseURL + UpdateFilePath,
          header: {
            Authorization: `${that.$storage.get("Token")}`,
          }, // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          formData: {
            user: "test",
          },
          success: (res) => {
            setTimeout(() => {
              console.log("上传成功", res, that.fileList1);
              let { data } = JSON.parse(res.data);
              resolve(data);
            }, 1000);
          },
        });
      });
    },
    // 模态框
    success() {
      this.showModel = true;
    },
    // 同意协议
    loginPrompt() {
      this.$message("请先阅读并同意下方协议", false);
    },
    // 提交表单
    submitUserForm() {
      let result;
      if (!this.technicianId && !this.switchVal) return this.loginPrompt();
      this.$refs.userForm
        .validate()
        .then(async (res) => {
          if (this.fileList1.length < 2) {
            uni.$u.toast("请上传身份证正反照图片");
            return;
          }
          if (this.fileList2.length < 1) {
            uni.$u.toast("请上传资格证书图片");
            return;
          }
          if (this.fileList3.length < 1) {
            uni.$u.toast("请上传工作形象照");
            return;
          }

          if (!this.technicianId) {
            result = await createModel(
              "65c08a445efd5153ff55d908",
              this.technicianInfo
            );
            this.showModel = false;
          } else {
            //修改表单数据
            result = await updateModel(
              "65c08a445efd5153ff55d908",
              this.technicianInfo,
              this.technicianId
            );
          }

          uni.$u.toast(result.msg);
          uni.navigateBack({
            delta: 1,
            duration: 600,
          });
        })
        .catch((errors) => {
          uni.$u.toast("校验失败");
        });
    },
    // 提交按钮
    submit() {
      if (!this.technicianId) {
        this.showModel = true;
      } else {
        this.submitUserForm();
      }
    },
    // 获取上传图片数据正确格式
    getUploadData(arr) {
      return arr.map((item) => {
        const { url, name } = item.url;
        if (url) {
          return {
            url,
            name,
            fileId: Date.now(),
          };
        } else {
          return {
            url: item.url.split(config.baseURL)[1],
            name: item.name,
            fileId: Date.now(),
          };
        }
      });
    },
    // 获取回显图片数据正确格式
    processFileList(arr) {
      return arr.map((item) => {
        item.url = config.baseURL + item.url;
        return item;
      });
    },
    // 选择地址
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.technicianInfo.address = res.address;
          this.technicianInfo.technician_address = `${res.latitude},${res.longitude}`;
        },
      });
    },
  },
  watch: {
    fileList1(val) {
      this.technicianInfo.idCard_img = this.getUploadData(val);
    },
    fileList2(val) {
      this.technicianInfo.certificate_img = this.getUploadData(val);
    },
    fileList3(val) {
      this.technicianInfo.work_img = this.getUploadData(val);
    },
  },
  async onLoad(options) {
    if (options.id) {
      let filterData = {
        currentPage: 1,
        pageSize: -1,
        filter: getSearchFilter({ _id: options.id }, { method: "eq" }),
      };
      const { data } = await getModelList(
        "65c08a445efd5153ff55d908",
        filterData
      );
      let response = data?.list?.[0];
      delete response._id;
      delete response.creatorTime;
      delete response.creatorUserId;
      this.technicianInfo = Object.assign(this.technicianInfo, response);
      this.technicianId = options.id;
      this.fileList1 = this.processFileList(this.technicianInfo.idCard_img);
      this.fileList2 = this.processFileList(
        this.technicianInfo.certificate_img
      );
      this.fileList3 = this.processFileList(this.technicianInfo.work_img);
    }
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.userForm.setRules(this.rules);
  },
};
</script>

<style lang="scss" scoped>
.settled {
  background-color: #fff;

  > button {
    margin-top: 30rpx;
  }
}
::v-deep .u-form {
  background-color: #fff;
  border-radius: 10rpx;

  &-item {
    padding: 0 30rpx;

    &__body {
      padding: 12px 0;
    }

    &__body__left__content__label {
      margin-left: 8rpx;
    }
  }

  input {
    text-align: right !important;
  }

  .u-icon--right {
    // margin-left: 8rpx;
  }
}

::v-deep .u-radio-group {
  width: fit-content;
  justify-content: flex-end;
}

::v-deep .u-textarea {
  margin-top: 20rpx;
}
::v-deep .u-upload__wrap {
  margin-top: 20rpx;
}

::v-deep .u-modal > .u-modal__title {
  font-size: 36rpx;
  color: #333333;
}
</style>
